package cn.android.support.v7.lib.sin.crown.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import cn.android.support.v7.lib.sin.crown.base.BaseView;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;

/**
 * 手写签名版本
 * Created by 彭治铭 on 2017/10/20.
 */

public class Signature extends BaseView {
    public Signature(Context context) {
        super(context);
        init();
    }

    public Signature(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private Path mPath;
    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;

    private void init() {
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeJoin(Paint.Join.ROUND);
        textPaint.setStrokeCap(Paint.Cap.ROUND);
        textPaint.setStrokeJoin(Paint.Join.ROUND);

        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(ProportionUtils.getInstance().adapterInt(10));
        paint.setColor(Color.BLUE);
        mPath = new Path();

    }

    //清除
    public void clear() {
        mPath.reset();
        invalidate();
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawPath(mPath, paint);
    }


    private void touch_start(float x, float y) {
        //mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }

    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
    }

    private void touch_up() {
        mPath.lineTo(mX, mY);
        //mPath.reset();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
        }
        return true;
    }

}
